package com.wechat.controller;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.fh.common.util.Base64Util;
import com.fh.common.util.StringUtils;
import com.wechat.config.prperties.WxPayProperties;
import com.wechat.core.annotation.Token;
import com.wechat.core.bean.Result;
import com.wechat.core.exception.NotLoginException;
import com.wechat.core.handler.LoginBean;
import com.wechat.core.handler.TokenUtil;
import com.wechat.models.request.LoginRequest;
import com.wechat.models.response.WxLoginResponse;
import com.wechat.service.user.WechatUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 程序名：.java<br>
 * 程序功能 <br>
 * 作成者：xianlin <br>
 * 日期：2019-11-15 11:16<br>
 * 修改履历 <br>
 * 项目名    状态      作成者      日期   <br>
 * --------------------------------------- <br>
 * 新规      xianlin   2019-11-15 11:16 <br>
 * ----------------------------- <br>
 */
@Slf4j
@Controller
@RequestMapping("wechat/share")
@Api(tags = "微商城分享功能")
public class WechatShareController extends BaseController{

    @Value("${wechat.share.baseUrl}")
    private String shareBaseUrl;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private TokenUtil tokenUtil;

    @GetMapping("shareConfig")
    @ResponseBody
    public Result<JSONObject> shareConfig(String url){
        JSONObject result=null;
        try {
            WxJsapiSignature wxJsapiSignature = wxMpService.createJsapiSignature(url);
            String shareUrl=shareBaseUrl  + "/" + this.getUserId()+"/"+ Base64Util.encodeData(url);
            result= (JSONObject) JSONObject.toJSON(wxJsapiSignature);
            result.put("shareUrl",shareUrl);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("微信分享功能wxConfig-init------,{}", e.getMessage());
        }
        return new Result<JSONObject>().result(result);
    }
    @GetMapping("config")
    @ResponseBody
    public Result<WxJsapiSignature> wxConfig(String url){
        WxJsapiSignature wxJsapiSignature = null;
        try {
            wxJsapiSignature = wxMpService.createJsapiSignature(url);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("微信分享功能wxConfig-init------,{}", e.getMessage());
        }
        return new Result<WxJsapiSignature>().result(wxJsapiSignature);
    }

    @GetMapping("index/{memberId}/{url}")
    @Token(required = false)
    public String share(@PathVariable String memberId,@PathVariable String url,String from,HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        //url采用base64加密
        String decodedUrl=Base64Util.decodeData(url);
        String code=httpServletRequest.getParameter("code");
        try{
            //此次请求是微信服务器回调请求
            if(!StringUtils.isEmpty(code)){
                WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
                String openId = wxMpOAuth2AccessToken.getOpenId();
                LoginRequest loginRequest=new LoginRequest();
                if(!StringUtils.isEmpty(memberId)){
                    loginRequest.setPrePartnerId(Integer.parseInt(memberId));
                }
                loginRequest.setOpenid(openId);
                WxLoginResponse result=wechatUserService.wxLogin(loginRequest);
                Cookie cookie=new Cookie("token",result.getToken());
                cookie.setPath("/");
                cookie.setDomain(wxPayProperties.getDomain());
                httpServletResponse.addCookie(cookie);
                return "redirect:"+decodedUrl;
            }
        }catch (WxErrorException e){
            e.printStackTrace();
        }
        try{
            LoginBean loginBean=tokenUtil.loginValidate(httpServletRequest,httpServletResponse);
            return "redirect:"+decodedUrl;
        }catch (NotLoginException e){
            String redirectUrl=shareBaseUrl  + "/" + memberId+"/"+ url;
            String wxLogin=String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s",
                    wxPayProperties.getAppId(), redirectUrl, "snsapi_userinfo", "");
            return "redirect:"+wxLogin;
        }
    }

}
